<template>
  <div class="recommend-container">
    <div class="container">
      <div class="page-header">
        <h1>推荐内容</h1>
        <p>为您精选的优质内容</p>
      </div>

      <!-- 内容列表 -->
      <div class="content-grid" v-loading="loading">
        <div 
          v-for="content in contentList" 
          :key="content.id"
          class="content-card"
          @click="viewContent(content.id)"
        >
          <!-- 内容封面 -->
          <div class="content-cover">
            <img 
              v-if="content.type === 'IMAGE'" 
              :src="getFileUrl(content.fileUrl)" 
              :alt="content.title"
              @error="handleImageError"
            />
            <div v-else-if="content.type === 'VIDEO'" class="video-cover">
              <img 
                v-if="content.thumbnailUrl" 
                :src="getFileUrl(content.thumbnailUrl)" 
                :alt="content.title"
                @error="handleImageError"
              />
              <div v-else class="video-placeholder">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="video-duration" v-if="content.duration">
                {{ formatDuration(content.duration) }}
              </div>
            </div>
            <div v-else class="document-cover">
              <el-icon><Document /></el-icon>
              <span>{{ getFileExtension(content.fileUrl) }}</span>
            </div>
            
            <!-- 内容类型标签 -->
            <div class="content-type-tag">
              <el-tag 
                :type="getContentTypeColor(content.type)" 
                size="small"
              >
                {{ getContentTypeName(content.type) }}
              </el-tag>
            </div>
          </div>

          <!-- 内容信息 -->
          <div class="content-info">
            <h3 class="content-title">{{ content.title }}</h3>
            <p class="content-description">{{ content.description }}</p>
            
            <!-- 作者信息 -->
            <div class="author-info">
              <el-avatar :size="24" :src="content.author?.avatar">
                {{ content.author?.nickname?.[0] || content.author?.username?.[0] }}
              </el-avatar>
              <span class="author-name">
                {{ content.author?.nickname || content.author?.username }}
              </span>
            </div>

            <!-- 统计信息 -->
            <div class="content-stats">
              <div class="stat-item">
                <el-icon><View /></el-icon>
                <span>{{ content.viewCount }}</span>
              </div>
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span>{{ content.likeCount }}</span>
              </div>
              <div class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ content.commentCount }}</span>
              </div>
            </div>

            <!-- 标签 -->
            <div class="content-tags" v-if="content.tags">
              <el-tag 
                v-for="tag in getTagList(content.tags)" 
                :key="tag"
                size="small"
                type="info"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore">
        <el-button 
          @click="loadMore" 
          :loading="loadingMore"
          type="primary"
          plain
        >
          加载更多
        </el-button>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && contentList.length === 0" class="empty-state">
        <el-empty description="暂无推荐内容">
          <el-button type="primary" @click="refreshContent">刷新</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { VideoPlay, Document, View, Star, ChatDotRound } from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const contentList = ref([])
const currentPage = ref(0)
const hasMore = ref(true)
const pageSize = 12

// 获取推荐内容
const getRecommendedContents = async (page = 0, append = false) => {
  try {
    if (page === 0) {
      loading.value = true
    } else {
      loadingMore.value = true
    }

    const response = await api.get('/contents/recommend', {
      params: {
        page,
        size: pageSize
      }
    })

    if (response.data.success) {
      const newContents = response.data.data.content
      if (append) {
        contentList.value.push(...newContents)
      } else {
        contentList.value = newContents
      }
      
      hasMore.value = !response.data.data.last
      currentPage.value = page
    }
  } catch (error) {
    ElMessage.error('获取推荐内容失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    getRecommendedContents(currentPage.value + 1, true)
  }
}

// 刷新内容
const refreshContent = () => {
  currentPage.value = 0
  hasMore.value = true
  getRecommendedContents(0, false)
}

// 查看内容详情
const viewContent = (contentId) => {
  router.push(`/content/${contentId}`)
}

// 获取文件URL
const getFileUrl = (url) => {
  if (!url) return ''
  return url.startsWith('http') ? url : `http://localhost:8080${url}`
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = ''
}

// 格式化时长
const formatDuration = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 获取文件扩展名
const getFileExtension = (url) => {
  if (!url) return 'FILE'
  const extension = url.split('.').pop()?.toUpperCase()
  return extension || 'FILE'
}

// 获取内容类型名称
const getContentTypeName = (type) => {
  const typeMap = {
    VIDEO: '视频',
    IMAGE: '图片',
    DOCUMENT: '文档'
  }
  return typeMap[type] || type
}

// 获取内容类型颜色
const getContentTypeColor = (type) => {
  const colorMap = {
    VIDEO: 'danger',
    IMAGE: 'success',
    DOCUMENT: 'warning'
  }
  return colorMap[type] || 'info'
}

// 获取标签列表
const getTagList = (tags) => {
  if (!tags) return []
  return tags.split(',').filter(tag => tag.trim()).slice(0, 3)
}

// 组件挂载时获取数据
onMounted(() => {
  getRecommendedContents()
})
</script>

<style scoped>
.recommend-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #333;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.content-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.content-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.content-cover {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.content-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-cover {
  position: relative;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f0f0f0;
  color: #999;
}

.video-placeholder .el-icon {
  font-size: 48px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.document-cover {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f8f9fa;
  color: #666;
}

.document-cover .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.document-cover span {
  font-size: 14px;
  font-weight: 500;
}

.content-type-tag {
  position: absolute;
  top: 8px;
  left: 8px;
}

.content-info {
  padding: 16px;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.author-name {
  margin-left: 8px;
  font-size: 14px;
  color: #666;
}

.content-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #999;
  font-size: 12px;
}

.stat-item .el-icon {
  font-size: 14px;
}

.content-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-item {
  font-size: 11px;
}

.load-more {
  text-align: center;
  margin: 40px 0;
}

.empty-state {
  text-align: center;
  margin: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 15px;
  }
  
  .content-cover {
    height: 160px;
  }
  
  .content-info {
    padding: 12px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .content-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .recommend-container {
    padding: 15px 0;
  }
}
</style> 